﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using WYJCore;

namespace WYJWeb
{
    public static class DataHelper
    {
        public static Dictionary<SqlKey, string> SqlTemplate = new Dictionary<SqlKey, string>
            {
                { SqlKey.CREATE, "CREATE {0} {1} "},
                { SqlKey.INSERT, "INSERT INTO {0} {1} VALUES ({2}) "},
                { SqlKey.DELETE, "DELETE FROM {0} "},
                { SqlKey.UPDATE, "UPDATE {0} SET {1} "},
                { SqlKey.SELECT, "SELECT {0} FROM {1} " },
                { SqlKey.DISTINCT, "SELECT DISTINCT {0} FROM {1} " },
                { SqlKey.WHERE, " WHERE {0} {1} {2} " },
                { SqlKey.ORDER, " ORDER BY {0} {1} " },
                { SqlKey.OFFSET, " OFFSET {0} rows FETCH next {1} rows only " },
                { SqlKey.AND, " AND {0} {1} {2} " },
                { SqlKey.OR, " OR {0} {1} {2} " },

                { SqlKey.ADD, " ALTER TABLE {0} ADD {1} {2} " },
                { SqlKey.DROP, " ALTER TABLE {0} DROP COLUMN {1} " },
                { SqlKey.ALTER, " ALTER TABLE {0} ALTER COLUMN {1} {2} " },
                { SqlKey.clearRows, " TRUNCATE TABLE {0}  " },

        };


        public static void Execute(this SqlCommand sqlCommand, string sql)
        {
            sqlCommand.CommandText = sql;
            sqlCommand.ExecuteNonQuery();
        }

        public static SqlDataReader Query(this SqlCommand sqlCommand, string sql,Action<SqlDataReader> action)
        {
            sqlCommand.CommandText = sql;
            var dataReader = sqlCommand.ExecuteReader();
            while (dataReader.Read())
            {
                action(dataReader);
            }
            dataReader.Close();
            return dataReader;
        }

        public static SqlDataReader Query(this SqlCommand sqlCommand, string sql, Action<SqlDataReader, int> action)
        {
            sqlCommand.CommandText = sql;
            var dataReader = sqlCommand.ExecuteReader();
            var result = 0;
            do
            {
                result++;
                while (dataReader.Read())
                {
                    action(dataReader, result);
                }

            }
            while (dataReader.NextResult());
            dataReader.Close();
            return dataReader;
        }

        public static bool IsModel(this Type type)
        {
            return type.GetInterface("IModel") == typeof(IModel);
        }
    }
}
